<?php

namespace app\admin\controller;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

use app\lib\exception\ParameterException;
use app\common\BaseHelper;
use app\common\Common;

use app\admin\model\Member as MemberMdl;
use app\admin\model\Memberhomeimg;
use app\admin\model\Organization;
use app\admin\model\Usersubmitexamine;
use app\admin\model\Ethnic;
use app\admin\model\Image;
use app\admin\model\Povertymember;
use app\admin\model\Villages;
use app\admin\model\Area;

use think\Db;
use think\Exception;
use think\Request;

class Member extends Base
{

    protected $isIframe = false;

    public function _initialize()
    {

        $this->accessAction = ['index', 'add', 'shenhe'];
        $this->exceptAction = ['checkIdentityNumber'];

        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['isDelete'] = ['neq', 1];
        $defaultWhere['shenheStatus'] = ['<', 2];  //过滤掉审核失败或审核中状态的数据
        $this->defaultWhere = $defaultWhere;

        $this->searchFields = [
            'name' => [
                'label'     => '姓名',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];
    }

    public function index(){
        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){
        // 名族
        $ethnics = Ethnic::order('sorting ASC')->select();
        $ethnicList = collection($ethnics)->toArray();
        // 文化程度
        $educationList = get_education();
        // 健康状况
        $healthList = get_health();

        $povertyreason = povertyreason();

        $this->assign('povertyreason',$povertyreason);
        $this->assign('ethnicList', $ethnicList);
        $this->assign('educationList', $educationList);
        $this->assign('healthList', $healthList);

        return parent::add($request);
    }

    /**
     * Add Post
     */
    public function addPost(Request $request, $redirect = ''){
        if(!$request->post('birthday')){
            $request->post(['birthday' => substr($request->post('identityNumber'),6,4).'-'.substr($request->post('identityNumber'),10,2).'-'.substr($request->post('identityNumber'),12,2)]);
        }
        if($request->post('partyTime')){
            $request->post(['partyTime' => strtotime($request->post('partyTime'))]);
        }
        $request->post(['shenheStatus' => 0]);

        //return parent::addPost($request, $redirect);
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();

            $identityNumber = $data['identityNumber'];
            $info = $model->where(['identityNumber' => $identityNumber])->find();
            if($info){
                // 将已删除的村民 进行更新
                $data['id'] = $info['id'];
                $data['createDate'] = time();
                $data['createOper'] = $this->admin->id;
                $data['isDelete'] = 2;
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            }else{
                // Insert data
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();
                $data['createOper'] = $this->admin->id;
                // $data['villageId'] = $this->admin->villageId;
                $result = $model->save($data);
            }

            if($result !== false) {
                // Query执行后的操作
                $model->_after_insert($data);

                // 写入日志
                $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                if ($redirect) {
                    return $this->success('添加成功！', $redirect);
                } else {
                    return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
                }
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('添加失败！');
        }
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        // 名族
        $ethnics = Ethnic::order('sorting ASC')->select();
        $ethnicList = collection($ethnics)->toArray();
        // 文化程度
        $educationList = get_education();
        // 健康状况
        $healthList = get_health();
        $povertyreason = povertyreason();

        $this->assign('povertyreason',$povertyreason);

        $id = $request->param('id');
        $imagesList = Image::where(['relatedId' => $id, 'tag' => 'imglist'])->select();
        $this->assign('imagesList', $imagesList);
        $this->assign('imgcount', count($imagesList));

        $poverty = Povertymember::alias('a')->join('member b','a.aidingId=b.id')->field('a.*,b.name')->where('memberId',$id)->find();
        // dump($poverty);die;
        $this->assign('poverty',$poverty);

        $this->assign('ethnicList', $ethnicList);
        $this->assign('educationList', $educationList);
        $this->assign('healthList', $healthList);

        return parent::edit($request);
    }

    /**
     * Edit Post
     */
    public function editPost(Request $request, $redirect = ''){
        if(!$request->post('birthday')){
            $request->post(['birthday' => substr($request->post('identityNumber'),6,4).'-'.substr($request->post('identityNumber'),10,2).'-'.substr($request->post('identityNumber'),12,2)]);
        }

        if($request->post('partyTime')){
            $request->post(['partyTime' => strtotime($request->post('partyTime'))]);
        }

        return parent::editPost($request, $redirect);
    }

    /**
     * Delete
     */
    public function delete(){
        $model = model($this->model);
        $request = $this->request;
        $id = $request->param('id');

        $member = $model->where('id',$id)->find();

        //判断是否为管理员，若是，则提示
        $operator = \app\admin\model\Operator::where(['memberId'=>$id,'isDelete'=>2])->find();
        if($operator) {
            return $this->error('该村民是管理员，请先去删除管理员');
        }

        // TODO 有扶贫项目和扶贫工作 是否还能删除

        if($member['isPoverty'] == 1) {// 是否是贫困户，若是，则删除povertymember表相关数据
            $delpoverty = db('povertymember')->where(['memberId' => $id])->delete();
        }

        $result = $model->where('id', $id)->update(['isDelete' => 1, 'shenheStatus' => 2, 'userId' => '']);
        $User = \app\admin\model\User::where('memberId',$id)->find();
        if($User){
            $User->memberId = Null;
            $User->save();
        }
        if($result !== false){
            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
            Common::adminLog($request, $logInfo);
            return $this->success('删除成功！', 'admin/' . strtolower($request->controller()) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    //居民审核列表
    public function shenhe(){
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model('Member');

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }

            $list = $model->where($where)->where('shenheStatus',['=',1],['=',2],['=',3],'OR')->limit($start, $length)->order($order)->select();
            foreach ($list as &$v){
                $v['city'] = getAreaName($v['cityId']);
                $v['xian'] = getAreaName($v['xianId']);
                $v['town'] = getAreaName($v['townId']);
                $v['village'] = getVillageName($v['villageId']);
            }
            $count = $model->where($where)->where('shenheStatus',['=',1],['=',2],['=',3],'OR')->count();
            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return $this->fetch('shenhe_list', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 居民审核详情
     * @return mixed
     * @throws ParameterException
     */
    public function shenhedetail(){
        $param = Request::instance()->param();
        if(!$param['id']){
            throw new ParameterException([
                'msg' => '非法提交'
            ]);
        }
        $Member = \app\admin\model\Member::get($param['id']);
        $Member['city'] = getAreaName($Member['cityId']);
        $Member['xian'] = getAreaName($Member['xianId']);
        $Member['town'] = getAreaName($Member['townId']);
        $Member['village'] = '';
        if($Member->villageId){
            $Villages = \app\admin\model\Villages::get($Member->villageId);
            $Member['village'] = $Villages->name;
        }
        if($Member->homeImg){
            $homeImg = explode(',',$Member->homeImg);
        }
        $Member['organizationname'] = '';
        if($Member->isParty == 1 && $Member->organizationId){
            $Organization = Organization::get($Member->organizationId);
            if($Organization){
                $Member['organizationname'] = $Organization->name;
            }
        }
        return $this->fetch('shenhedetail',[
            'data' => $Member,
            'homeImg' => isset($homeImg)?$homeImg:''
        ]);
    }

    /**
     * 审核逻辑
     */
    public function shenhePost(Request $request){
        if(request()->isPost()){
            Db::startTrans();
            try{
                $param = $request->param();
                $Member = \app\admin\model\Member::get($param['id']);
                if($Member && $Member->shenheStatus == 2){
                    if($Member->isDelete == 1){
                        $Member->isDelete = 2;
                    }
                    $Member->shenheStatus = 1;
                    $Member->failMsg = NULL;
                    $Member->save();
                    //图片关联处理
                    Image::whereIn('imgUrl',[$Member->avatar,$Member->cardImg])->update(['relatedId'=>$Member->id,'relatedTable'=>'member']);
                    Image::whereIn('imgUrl',explode(',', $Member->homeImg))->update(['relatedId'=>$Member->id,'relatedTable'=>'member','tag'=>'imglist']);

                    $User = \app\admin\model\User::get($Member->userId);
                    if($User){
                        $User->memberId = $Member->id;
                        $User->save();
                        Db::commit();
                        return $this->success('审核成功！', 'admin/' . strtolower($request->controller()) . '/shenhe');
                    }

                }else{
                    throw new ParameterException([
                        'msg' => '不能重复审核'
                    ]);
                }
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('网络错误');
                
            }
        }
    }

    //审核不通过
    public function noshenhePost(Request $request){
        if(request()->isPost()){
            $param = $request->param();
            $Member = \app\admin\model\Member::get($param['id']);
            if($Member && $Member->shenheStatus == 2){
                $Member->shenheStatus = 3;
                $Member->failMsg = $param['failMsg'];
                $Member->save();
                return $this->success('提交成功！', 'admin/' . strtolower($request->controller()) . '/shenhe');
            }else{
                return $this->error('不能重复审核！', 'admin/' . strtolower($this->model) . '/shenhe');
            }
        }
    }

    /**
     * 检查身份证号是否已存在
     */
    public function checkIdentityNumber(){
        if($this->request->isAjax()){
            $identityNumber = $this->request->param('identityNumber');
            $model = model($this->model);

            $result = $model->where(['identityNumber' => $identityNumber, 'isDelete' => 2])->field('identityNumber')->find();

            if($result){
                return json(['status' => 1]);
            }else{
                return json(['status' => 0]);
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }

            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }

    /**
     * 获取机构
     */
    public function getInstitution(){
        $param = $this->request->param();
        $where = [];
        if($param['townId']){
            $where['townId'] = $param['townId'];
        }
        $model = model('Institution');
        $data = $model->where($where)->field('id, name')->select();

        $html = '';
        if($data){
            foreach($data as $item){
                $html .= "<option value='{$item['id']}'>{$item['name']}</option>";
            }
        }

        return json($html);
    }

    /**
     * 获取部门
     */
    public function getDepartment(){
        $param = $this->request->param();
        $where = [
            'institutionId' => $param['institutionId']
        ];
        $model = model('Department');
        $data = $model->where($where)->field('id, name')->select();

        $html = '';
        if($data){
            foreach($data as $item){
                $html .= "<option value='{$item['id']}'>{$item['name']}</option>";
            }
        }

        return json($html);
    }

    /**
     * 下载Excel模板
     */
    public function downloadTemplate(){
        $param = $this->request->param();
        $townId = $param['townId'];

        $xlsTitle = 'Templete';
        $spreadsheet = new Spreadsheet();
        $spreadsheet->setActiveSheetIndex(0);
        $spreadsheet->getActiveSheet()->setTitle($xlsTitle);

        $spreadsheet->getActiveSheet()->setCellValue('A1', '村民基本信息');
        $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);

        $index0 = 2;
        $cellArray0 = array(
            'A' => '所属镇',
            'B' => '所属村(可选填)',
            'C' => '姓名',
            'D' => '性别(1=男|2=女)',
            'E' => '出生日期(可选填，格式：2018-08-08)',
            'F' => '身份证号',
            'G' => '手机号(可选填)',
            'H' => '民族',
            'I' => '文化程度',
            'J' => '健康状况',
            'K' => '详细住址',
            'L' => '是否为党员(1=是|2=否)',
            'M' => '组织(党员必填项)',
            'N' => '职务名称(党员必填项)',
            'O' => '入党时间(党员必填项，格式：2018-08-08)',
        );
        foreach ($cellArray0 as $key0 => $cell0) {
            $spreadsheet->getActiveSheet()->setCellValue($key0 . $index0, $cell0);
            //$spreadsheet->getActiveSheet()->getColumnDimension($key0)->setWidth(10);
            //$spreadsheet->getActiveSheet()->getColumnDimension($key0)->setAutoSize(true);
        }
        /*
        $list = 'select1,select2,select3';
        $objValidation = $spreadsheet->getActiveSheet()->getCell('B2')->getDataValidation(); // 从第二行开始有下拉样式
        $objValidation->setType(DataValidation::TYPE_LIST)
            ->setErrorStyle(DataValidation::STYLE_INFORMATION)
            ->setAllowBlank(false)
            ->setShowInputMessage(true)
            ->setShowErrorMessage(true)
            ->setShowDropDown(true)
            ->setErrorTitle('输入的值有误')
            ->setError('您输入的值不在下拉框列表内.')
            ->setPromptTitle('设备类型')
            ->setPrompt('')
            //->setFormula1('mySheet2!$A$1:$A$3'); //把sheet名为mySheet2的 A1,A2,A3 作为选项
            ->setFormula1('"' . $list . '"'); // 左右引号不要去掉，去掉会出错
        */

        $cellArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB'];
        //$spreadsheet->getActiveSheet()->setCellValue('A4', '民族');
        // 文化程度
        $spreadsheet->getActiveSheet()->setCellValue('A4', '文化程度');
        $spreadsheet->getActiveSheet()->getStyle('A4')->getFont()->setBold(true);
        $index1 = 5;
        $educationList = get_education();
        $i1 = 0;
        foreach ($educationList as $key1 => $cell1) {
            $spreadsheet->getActiveSheet()->setCellValue($cellArray[$i1] . $index1, $cell1);
            $i1 ++;
        }

        // 健康状况
        $spreadsheet->getActiveSheet()->setCellValue('A7', '健康状况');
        $spreadsheet->getActiveSheet()->getStyle('A7')->getFont()->setBold(true);
        $index2 = 8;
        $healthList = get_health();
        $i2 = 0;
        foreach ($healthList as $key2 => $cell2) {
            $spreadsheet->getActiveSheet()->setCellValue($cellArray[$i2] . $index2, $cell2);
            $i2 ++;
        }

        $town = db('area')->where(['id' => $townId])->value('name');
        // 镇下的村子
        $spreadsheet->getActiveSheet()->setCellValue('A10', $town . '下的村子');
        $spreadsheet->getActiveSheet()->getStyle('A10')->getFont()->setBold(true);
        $index3 = 11;
        $villageList = Villages::where(['townId' => $townId])->field('name')->select();
        foreach ($villageList as $key3 => $cell3) {
            $spreadsheet->getActiveSheet()->setCellValue('A' . ($index3), $cell3['name']);
            $index3 ++;
        }

        // 镇下的组织
        $index4 = 11 + count($villageList) + 2;
        $spreadsheet->getActiveSheet()->setCellValue('A' . ($index4 -1), $town . '下的组织');
        $spreadsheet->getActiveSheet()->getStyle('A' . ($index4 -1))->getFont()->setBold(true);
        $organizationList = Organization::where(['townId' => $townId, 'isDelete' => 2])->field('name,villageId')->select();
        foreach ($organizationList as $key4 => $cell4) {
            $villageName = Villages::where(['id' => $cell4['villageId']])->value('name');
            $spreadsheet->getActiveSheet()->setCellValue('A' . ($index4), $cell4['name']);
            $spreadsheet->getActiveSheet()->setCellValue('B' . ($index4), $villageName);
            $index4 ++;
        }

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'member' . DS . 'templete' . DS . date('Y-m-d');
        $fileName = $filePath . '/member_templete_' . date('y-m-d-H-i-s');

        //检查文件或目录是否存在
        if(!file_exists($filePath)){
            mkdir($filePath, 0777, true);
        }
        $writer = new Xlsx($spreadsheet);
        //$writer->save($fileName . '.xls'); // or .xlsx

        $xlsTitle = iconv('utf-8', 'gb2312', $xlsTitle); // 文件名称
        $downFileName = basename($fileName,".".pathinfo($fileName, PATHINFO_EXTENSION));
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$downFileName.xls"); // attachment 新窗口打印,inline 本窗口打印

        $writer->save('php://output');
        exit;
    }

    /**
     * 导入数据
     */
    public function import(){
        $file = request()->file('csv_file');

        Db::startTrans();
        try {
            $filePath = ROOT_PATH . 'public' . DS . 'upload';
            $info = $file->move($filePath);
            $fileName = $info->getSaveName();
            //$fileName = 'user_' . date('y-m-d-H-i-s') . '.' . substr($file,strripos($file,'.')+1);
            //move_uploaded_file($file, iconv("UTF-8","gb2312", $filePath . DS . $fileName));
            $fileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($filePath . DS . $fileName);
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($fileType);
            // 设置编码
            if(strtolower($fileType) == 'csv'){
                $reader->setInputEncoding('CP936'); // 只对csv文件有效
            }
            $spreadsheet = $reader->load($filePath . DS . $fileName);

            $sheetData = $spreadsheet->getActiveSheet()->toArray();
            if(count($sheetData) <= 1){
                return json(['status' => 0, 'msg' => '未找到文件内容，请填写数据。']);
            }
            foreach ($sheetData as $key => $val) {
                if($key == 0){
                    continue;
                }
                if(count($val) < 15){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '文件内容不正确，请按照模板来填写内容。']);
                }
                $townId = Area::where(['name' => $val[0]])->value('id');
                if(!$townId){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '未找到' . $val[0]]);
                }
                $areaIds = $this->getParentIdsByTownId($townId);
                if($val[1]){
                    $villageId = Villages::where(['name' => $val[1]])->value('id');
                    if(!$villageId){
                        Db::rollback();
                        return json(['status' => 0, 'msg' => '未找到' . $val[1]]);
                    }
                }else{
                    $villageId = 0;
                }

                // 必填字段 验证
                if(!$val[2] || !$val[5]){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '姓名、身份证号等是必填字段']);
                }

                // 检查身份证号是否存在
                $identityNumber = MemberMdl::where(['identityNumber' => $val[5], 'isDelete' => 2])->value('identityNumber');
                if($identityNumber){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '身份证号 '. $val[5] .' 已存在！']);
                }

                // 民族
                $ethnicId = Ethnic::where(['name' => $val[7]])->value('id');
                if(!$ethnicId){
                    $ethnicId = Ethnic::where(['name' => '汉族'])->value('id');
                }
                // 文化程度
                $educationArr = get_education();
                $education = 1;
                foreach($educationArr as $eduKey => $eduValue){
                    if($eduValue == $val[8]){
                        $education = $eduKey;
                        break;
                    }
                }
                // 健康状况
                $healthArr = get_health();
                $health = 1;
                foreach($healthArr as $healthKey => $healthValue){
                    if($healthValue == $val[9]){
                        $health = $healthKey;
                        break;
                    }
                }
                // 是否是党员
                $organizationId = $job = $partyTime = '';
                if($val[11] == 1){
                    // 组织
                    if($villageId != 0){
                        // 找到该村下的组织
                        $organizationList = Organization::where(['villageId' => $villageId])->field('name')->select();
                        $organizationList = array_column($organizationList, 'name');
                        if(!in_array($val[12], $organizationList)){
                            Db::rollback();
                            return json(['status' => 0, 'msg' => $val[1] . '下面没有 '. $val[12] .'组织！']);
                        }
                    }
                    $organizationId = Organization::where(['name' => $val[13]])->value('id');
                    $job = $val[13];
                    $partyTime = strtotime($val[14]);
                }

                $data = [
                    'id'                 => BaseHelper::getUUID(),
                    'cityId'             => $areaIds['cityId'],
                    'xianId'             => $areaIds['xianId'],
                    'townId'             => $townId,
                    'villageId'          => $villageId,
                    'name'               => $val[2],
                    'gender'             => in_array($val[3], [1, 2]) ? $val[3] : 1,
                    'birthday'           => date('Y-m-d', strtotime($val[4])),
                    'identityNumber'     => $val[5],
                    'mobile'             => $val[6],
                    'ethnicId'           => $ethnicId,
                    'education'          => $education,
                    'health'             => $health,
                    'address'            => $val[10],
                    'isParty'            => $val[11],
                    'organizationId'     => $organizationId,
                    'job'                => $job,
                    'partyTime'          => $partyTime,
                    'createDate'         => time(),
                    'createOper'         => $this->admin->id,
                    'shenheStatus'       => 0
                ];

                $memberInfo = MemberMdl::where(['identityNumber' => $val[5]])->find();
                if($memberInfo){
                    // 将已删除的村民 进行更新
                    $data['id'] = $memberInfo['id'];
                    $data['createDate'] = time();
                    $data['createOper'] = $this->admin->id;
                    $data['isDelete'] = 2;
                    $result = MemberMdl::allowField(true)->save($data, ['id' => $data['id']]);
                }else{
                    $result = MemberMdl::insert($data);
                }

                if($result === false){
                    Db::rollback();
                    return json(['status' => 0, 'msg' => '导入失败！']);
                }
            }
            @unlink($filePath . DS . $fileName);

            Db::commit();
            return json(['status' => 1, 'msg' => '导入成功！']);
        } catch (\Exception $e){
            Db::rollback();
            $msg = $e->getMessage();
            //$msg = '导入失败，请严格按照模板来填写内容。';
            return json(['status' => 0, 'msg' => $msg]);
        }

        return json(['status' => 0, 'msg' => $msg]);
    }

    /**
     * 导出数据
     */
    public function export(){
        $param = $this->request->param();

        $where = [
            'isDelete' => 2,
            'shenheStatus' => ['<',2]
        ];
        if(!empty($param['cityId'])){
            $where['cityId'] = $param['cityId'];
        }
        if(!empty($param['xianId'])){
            $where['xianId'] = $param['xianId'];
        }
        if(!empty($param['townId'])){
            $where['townId'] = $param['townId'];
        }
        if(!empty($param['villageId'])){
            $where['villageId'] = $param['villageId'];
        }
        if(!empty($param['name'])){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }

        $model = model($this->model);
        $data = $model->where($where)->order('createDate', 'asc')->select();
        if(count($data) <= 0){
            $this->error('没有数据！', url('admin/member/index'));
        }
        $areaDB = db('area');
        $villageDB = db('villages');
        $organizationDB = db('organization');
        foreach ($data as $key => $val) {
            // 所属城市
            $val['cityId'] = $areaDB->where(['id' => $val['cityId']])->value('name');
            // 所属县
            $val['xianId'] = $areaDB->where(['id' => $val['xianId']])->value('name');
            // 所属镇
            $val['townId'] = $areaDB->where(['id' => $val['townId']])->value('name');
            // 所属村
            $val['villageId'] = $villageDB->where(['id' => $val['villageId']])->value('name');
            // 是否为贫困户
            switch ($val['isPoverty']) {
                case 1: $val['isPoverty'] = '是'; break;
                case 2: $val['isPoverty'] = '否'; break;
                default : $val['isPoverty'] = '否'; break;
            }
            // 是否为党员
            switch ($val['isParty']) {
                case 1: $val['isParty'] = '是'; break;
                case 2: $val['isParty'] = '否'; break;
                default : $val['isParty'] = '否'; break;
            }
            // 所属组织
            if($val['organizationId']){
                $val['organizationId'] = $organizationDB->where(['id' => $val['organizationId']])->value('name');
            }else{
                $val['organizationId'] = '';
            }
            // 入党时间
            if($val['partyTime']){
                $val['partyTime'] = date('Y-m-d', $val['partyTime']);
            }else{
                $val['partyTime'] = '';
            }
            $val['identityNumber'] = (string) $val['identityNumber'];
        }
        $cellName = array(
            'A' => ['id', '用户编号'],
            'B' => ['cityId', '所属城市'],
            'C' => ['xianId', '所属县'],
            'D' => ['townId', '所属镇'],
            'E' => ['villageId', '所属村'],
            'F' => ['createDate', '创建时间'],
            'G' => ['updateDate', '更新时间'],
            'H' => ['name', '名称'],
            'I' => ['avatar', '头像'],
            'J' => ['gender', '性别'],
            'K' => ['birthday', '生日'],
            'L' => ['identityNumber', '身份证号'],
            'M' => ['mobile', '手机号码'],
            'N' => ['ethnicId', '名族'],
            'O' => ['education', '文化程度'],
            'P' => ['health', '健康状况'],
            'Q' => ['isPoverty', '是否为贫困户'],
            'R' => ['address', '详细地址'],
            'S' => ['isParty', '是否为党员'],
            'T' => ['organizationId', '所属组织'],
            'U' => ['job', '职务名称'],
            'V' => ['partyTime', '入党时间'],
        );

        $filePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'csv' . DS . 'member' . DS . date('Y-m-d');
        $fileName = $filePath . '/member_' . date('y-m-d-H-i-s');

        $excel = new Excel();
        $excel->exportExcel('村民', $data, $cellName, $filePath, $fileName);

        return redirect('admin/member/index');
    }

}